package server.core;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import server.client.Client;
import server.client.ClientListener;
import server.client.ClientSender;
import server.constants.core.ILogConstants;
import server.output.Log;

/**
 * Der eigentliche ChatServer
 * 
 * @author DarXun
 */
public class ChatServer {

	private static ChatServer instance;

	public static final int SERVER_PORT = 4096;

	@SuppressWarnings("boxing")
	private ChatServer() {
		ServerSocket serverSocket = null;

		try {
			serverSocket = new ServerSocket(SERVER_PORT);
			Log.writeLn(ILogConstants.SERVER_STARTED, SERVER_PORT);
		} catch (IOException ex) {
			Log.writeLn(ILogConstants.ERROR_LISTENING, SERVER_PORT);
			ex.printStackTrace();
		}

		if (serverSocket != null) {
			// SeverDispatcher starten...
			ServerDispatcher dispatcher = new ServerDispatcher();
			dispatcher.start();

			// Connections akzeptieren und Clients handlen
			while (true) {
				try {
					Socket clientSocket = serverSocket.accept();

					Client client = new Client();
					client.setSocket(clientSocket);

					ClientListener clientListener = new ClientListener(client,
							dispatcher);
					ClientSender clientSender = new ClientSender(client,
							dispatcher);

					client.setListener(clientListener);
					client.setSender(clientSender);

					clientListener.start();
					clientSender.start();

					dispatcher.addClient(client);
				} catch (IOException ex) {
					ex.printStackTrace();
				}
			}
		}
	}

	/**
	 * Gibt die Instanz des Servers zurück (Singleton)
	 * 
	 * @return Die ChatServer Instanz
	 */
	public static ChatServer getInstance() {
		if (instance == null) {
			instance = new ChatServer();
		}

		return instance;
	}
}
